<style lang="scss">
  .block__title{
    margin: 25px 0 6px;
    padding:0 10px ;
    font-size: 14px;
    color: #666666;
  }
  .channel-icon{

  }
  .channel-list{
    box-shadow: #e7e7e7 0px  4px 5px;
    border-radius: 10px;
  }
  .channel-item{
    background: white;
    display: flex;
    align-items: center;
    .l{
      text-align: center;
      padding: 0 10px;
    }
    .c{
      flex: 1;
      padding-left: 10px;
      h3{
        font-weight: normal;
        font-size: 16px;
      }
    }
    .r{
      text-align: center;
      line-height: 40px;
      width: 40px;
      height: 60px;
    }
  }

  .pay-info{
    box-shadow: #e7e7e7 0px  4px 5px;
    background: white;
    border-radius: 0px;

    /*margin-bottom: 15px;*/
  }

  .pay-btn{
    margin-top: 10px;
    background: $fun-primary-color;
    color: white;
    border: none;
    box-shadow: #e7e7e7 0 0px  4px 4px;
    &.disabled{
      box-shadow: #e7e7e7 0 0px  0px 0px;
      background: $fun-gray-color;
    }
  }

</style>
<template>
  <div class="page-wrap" v-if="order.id">

    <div class="pay-info m-10 p-10">
      <div class="flex flex-justify-between m-b-6 fz-14 c6"><span>支付金额:</span>   <span class="price-selling"> ￥{{ order.pay_price }}</span></div>
      <div class="flex flex-justify-between order_no fz-14 c6"><span>订单编号:</span>  <span class="font12"> {{ order.order_no }}</span></div>
    </div>

    <div class="pay-info m-10 p-10">
      <div class="flex flex-justify-between m-b-6 fz-14 c6"><span>商品总价:</span>   <span class=""> {{ order.price_goods }}</span></div>
<!--      <div class="m-b-6 fz-14 c6"><span>押金金额:</span>   <span class=""> {{ order.deposit }}</span></div>-->
      <div class="flex flex-justify-between m-b-6 fz-14 c6"><span>会员优惠:</span>   <span class=""> -{{ order.deduction_money||0.00 }}</span></div>
      <div class="flex flex-justify-between m-b-6 fz-14 c6"><span>代金券抵扣:</span>   <span class=""> -{{ order.coupon_money||0.00 }}</span></div>
      <div class="flex flex-justify-between m-b-6 fz-14 c6"><span>物流费用:</span>   <span class=""> {{ order.price_express||0.00 }}</span></div>
    </div>

    <!--<div class="block__title">支付渠道</div>-->
    <radio-group class="p-10" @change="radioChange">
      <div class="channel-list bg-white p-t-10">
        <label class="channel-item p-10" v-for="(item,idx) in channel" :key="idx"  >
          <div class="l"><layout-icon class="channel-icon" :size="item.size"  :color="item.color" :type="item.icon" /></div>
          <div class="c"><h3 class="m-b-4">{{ item.title }}</h3><span class="c9 fz-12">{{ item.text }}</span></div>
          <div class="r"><radio :checked="idx===channelIndex" color="#06ad56" style="transform: scale(0.8)" :value="item.name"  /></div>
        </label>
      </div>
    </radio-group>

    <div class="m-15" >
      <button @click="pay" class="pay-btn" :class="{disabled:channelIndex==null}" :disabled="channelIndex==null">立即支付</button>
    </div>

  </div>
</template>

<script>
import { confirm, error, linkToEasy, modal, toast } from '@/common/fun'
import { pageMixin, WX_JSSDK_INIT } from '@/mixins'
import { getAuthUrl, getOrderBaseInfo, unifyPay, userUniLogin } from '@/api/user'
import LayoutIcon from '@/components/layout-icon/layout-icon'
import { findArrayIdx, GetQueryByString } from '@/common/helper'
import { getEnv } from '@/common/request'
import Promisify from '@/common/Promisify'
import Storage from '@/common/Storage'
import { Exception } from '@/common/Exception'

export default {
  components: { LayoutIcon },
  mixins: [pageMixin],
  data: function () {
    return {
      // JSSDK_INIT: false, // 不要自己初始化
      channel: [
        // { title: '支付宝支付', size: 32, name: 'ali', icon: 'icon-umidd17', color: '#0AE', text: '方便的支付' },
        // 有env参数了,可以退役了兄弟
        { title: '微信支付', size: 32, name: 'wx', icon: 'icon-weixinzhifu', color: '#00d500', text: '推荐用此支付方式' }
        // { title: '银联支付', size: 32, name: 'union', icon: 'https://qingclouds-server.oss-cn-shanghai.aliyuncs.com/ea5a8633b1146831/7346e1731bd99290.png', color: '#007b83', text: '银联' },
        // { title: '现金支付', size: 32, name: 'pos', icon: 'icon-yue1', color: '#ff7800', text: '此方式须有店员在旁边配合' }
      ],
      order: {},
      channelIndex: null,
      order_no: ''
    }
  },
  methods: {
    radioChange (e) {
      console.log(e.detail.value)
      const idx = findArrayIdx(this.channel, { name: e.detail.value })
      console.log(idx)
      if (idx !== false) this.channelIndex = Number(idx)
    },
    async _init_func () {
      const orderInfo = await getOrderBaseInfo({ order_no: this.order_no }).then(res => res.data).catch(err => { throw Error(err.msg) })
      console.log(orderInfo)
      this.order = orderInfo
    },
    /**
     * 公众号支付以及h5支付
     */
    async payByH5 () {
      const env = getEnv()
      if (env === 'wx_mp') {
        // 如果url有code去掉
        let {
          origin,
          pathname,
          search,
          hash
        } = window.location
        const strArr = []
        // 如果已经有code了,那么就只要一个order_no
        if (search.indexOf('code') !== -1) {
          const tempArr = search.split('&')
          for (var i of tempArr) {
            // 过滤多余的参数
            if (i.indexOf('order_no') !== -1) {
              strArr.push(i)
            }
          }
          console.log(strArr)
          let newSearchStr = strArr.join('&')
          if (newSearchStr.indexOf('?') === -1) {
            newSearchStr = '?' + newSearchStr
          }

          search = newSearchStr
        }
        const REDIRECT_URI = origin + pathname + search + hash

        const wxAuthUrl = await getAuthUrl({ REDIRECT_URI }).then(res => res.data).catch((err) => {
          throw Error(err.msg)
        })
        console.log('wxAuthUrl result is ', wxAuthUrl)
        location.replace(wxAuthUrl)
      }
    },
    // 微信app
    payByWxApp () {

    },
    // 微信小程序支付
    async payByWxMp () {
      const wxLoginRt = await Promisify('login').catch(() => {
        throw Error('微信login错误')
      })
      const { code } = wxLoginRt

      const payConfStr = await unifyPay({
        channel: getEnv(),
        code, // 微信小程序必传
        order_no: this.order_no
      }).then(res => res.data).catch(err => {
        modal({
          title: '获取支付配置失败',
          content: err.msg
        })
      })

      var payConfig = JSON.parse(payConfStr)

      const provider = 'wxpay'

      uni.requestPayment({
        timeStamp: payConfig.timeStamp,
        nonceStr: payConfig.nonceStr,
        package: payConfig.package,
        signType: 'MD5',
        paySign: payConfig.paySign,
        provider,
        success: (res) => {
          var path = '/pages/order/index'
          toast('支付成功')
          if (Storage.get('order_forward_url')) {
            path = Storage.get('order_forward_url')
          }
          setTimeout(() => {
            linkToEasy(path)
          }, 2000)
        },
        fail: (err) => {
          console.log(err)
          const { errMsg } = err
          if (errMsg === 'requestPayment:fail cancel') {
            error('用户取消支付')
            return
          }
          modal({
            title: '支付失败',
            content: err.errMsg
          })
        }
      })
    },
    pay () {
      // #ifdef APP-PLUS
      this.payByWxApp()
      // #endif

      // #ifdef H5
      this.payByH5()
      // #endif

      // #ifdef MP-WEIXIN
      this.payByWxMp()
      // #endif

      // #ifdef MP-TOUTIAO

      // #endif

      // #ifdef MP-ALIPAY

      // #endif

      // #ifdef MP-BAIDU

      // #endif

      // var post = { order_no: this.order_no, channel: this.channel[this.channelIndex].name }; var _self = this
      // if (isWx()) {
      //   post.openid = localStorage.getItem('wx_pub_openid')
      // }
      // if (!emptyObject(post)) return
      //
      // // 线下支付的订单
      //
      // if (post.channel === 'wx_wap') {
      //   _self.vant.alertMsg('网页暂不支持微信支付')
      //   return
      // }
      //
      // unifyPay(post).then(res => {
      //   if (res.body.code !== 1) {
      //   } else {
      //     // 处理线下支付的情况
      //     if (post.channel === 'pos') {
      //       this.vant.confirm('申请已提交，请尽快完成线下付款', '操作提示', '已付款', '取消').then(function (action) {
      //         _self.$router.replace({ path: '/orderDetail?id=' + _self.order.id })
      //       }).catch(function (action) {
      //
      //       })
      //       return
      //     }
      //
      //     _self.vant.loading('正在唤起支付', 1)
      //
      //     try {
      //       unifyPayFun(this.channel[this.channelIndex].name, JSON.parse(res.data.data)).then(res => {
      //         // _self.vant.success('支付成功');
      //
      //         this.vant.confirm('操作成功，请选择后续操作', '操作提示', '查看订单', '留在这里').then(function (action) {
      //           _self.$router.replace({ path: '/order' })
      //         }).catch(function (action) {
      //
      //         })
      //
      //         // _self.$router.push({ name: 'order' });
      //       }).catch(e => {
      //         _self.vant.alertMsg('支付失败' + e)
      //
      //         this.vant.confirm('支付失败,请选择后续操作', '操作提示', '查看订单', '留在这里').then(function (action) {
      //           _self.$router.replace({ path: '/order' })
      //         }).catch(function (action) {
      //
      //         })
      //
      //         // _self.$router.push({ name: 'order' });
      //       })
      //     } catch (e) {
      //       console.log(e.message)
      //     }
      //   }
      //
      //   // 如果当前账户没有open_id，就要去拿了
      //   if (res.body.code === -1) {
      //     _self.vant.showMsg('公众号需要获取openid')
      //
      //     getAuthUrl({ channel: 'wechat_pub_pay', redirect: location.href }).then(res => {
      //       if (res.body.code === 1) {
      //         sessionStorage.setItem('PAY_TEMP_PATH', window.location.href)
      //         location.replace(res.body.data)
      //       }
      //     }).catch(res => {
      //       _self.vant.error(res.body.msg || '获取openid失败')
      //     })
      //   }
      //
      //   if (res.body.code != 1 && res.body.code != -1) this.vant.error(res.body.msg || '获取支付信息失败')
      // })
    },
    async _init_pay_bywap () {
      const code = GetQueryByString(location.href, 'code')
      const access_token = Storage.get('access_token')
      // 可以确定是微信支付了
      if (code && access_token) {
        // 如果code相同，则代表code重复
        if (code === Storage.get('wxpay_temp_code')) {
          error('code重复使用')
          return
        }

        Storage.set('wxpay_temp_code', code)
        const payChannelIdx = findArrayIdx(this.channel, { name: 'wx' })
        if (payChannelIdx !== false) this.channelIndex = payChannelIdx
        const payConfStr = await unifyPay({
          channel: getEnv(),
          code, // 微信小程序必传
          order_no: this.order_no
        }).then(res => res.data).catch(err => {
          modal({
            title: '获取支付配置失败',
            content: err.msg
          })
        })

        var payConfig = JSON.parse(payConfStr)
        console.log(payConfig)
        WX_JSSDK_INIT(this).then((wxEnv) => {
          wxEnv.chooseWXPay({
            timestamp: payConfig.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
            nonceStr: payConfig.nonceStr, // 支付签名随机串，不长于 32 位
            package: payConfig.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
            signType: payConfig.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
            paySign: payConfig.paySign, // 支付签名
            success: function (res) {
              toast('支付成功')
              setTimeout(() => {
                this.$linkTo('/pages/order/index')
              }, 2000)
            },
            fail: function (err) {
              console.log(err)
              const { errMsg } = err
              if (errMsg === 'requestPayment:fail cancel') {
                error('用户取消支付')
                return
              }
              modal({
                title: '支付失败',
                content: err.errMsg
              })
            }
          })
        }).catch(err => { Exception.handle(err) })
      }
    }
  },
  onLoad (options) {
    this.order_no = options.order_no
    if (!this.order_no) {
      confirm({
        content: '参数缺失',
        showCancel: false
      }).then(() => { this.$back() })
      return
    }
    this._init_func()
  },
  created () {
    if (getEnv() === 'wx_mp') {
      this._init_pay_bywap()
    }
  }
}

//     wepy.request({
//       url: '/order/unifyPay',
//       method: 'post',
//       data: {
//         channel: 'wx_mini',
//         order_no: order_no,
//       },
//       success: res => {
//
//         var payConfig = JSON.parse(res.data.data);
//
//
//         wx.requestPayment({
//           timeStamp: payConfig.timeStamp,
//           nonceStr: payConfig.nonceStr,
//           package: payConfig.package,
//           signType: 'MD5',
//           paySign: payConfig.paySign,
//           success(res) {
//
//             Toast.success('支付成功')
//
//             var order_forward_url = wx.getStorageSync('order_forward_url')
//             wx.removeStorageSync('order_forward_url')
//
//             if(order_forward_url){
//               setTimeout(function() {
//                 wx.redirectTo({
//                   url: order_forward_url
//                 })
//               },1000)
//             }else{
//
//               setTimeout(function() {
//                 wx.switchTab({
//                   url: '/pages/home'
//                 })
//               },1000)
//
//             }
//
//           },
//           fail(res) {
//             Toast.success('支付失败');
//             setTimeout(function() {
//               wx.switchTab({
//                 url: '/pages/home'
//               })
//             },1500)
//           }
//         })

</script>
